xquery version "1.0-ml";
module namespace jqstore="http://jqstore.org/jqstore";
import module namespace config="http://jqstore.org/config" at "config.xqy";
declare option xdmp:mapping "false";

declare function jqstore:rewrite() {
	let $request := xdmp:get-request-url()
	let $url := '/jqstore/dispatch.xqy?originalRequest='
	let $requestMethod := xdmp:get-request-method()
	return
		if(fn:starts-with($request,$config:path)) then
			if ($requestMethod eq "GET")
			then 
				(: Duplicate parameters for the request :) 
				fn:string-join((
					fn:concat($url, xdmp:url-encode($request)),
						for $paramName in xdmp:get-request-field-names()
						for $value in xdmp:get-request-field($paramName)
						return fn:concat($paramName,'=',$value)
					),'&amp;')
			else 
				(: We already have the request parameters in the POST body; so don't duplicate them. :)
				fn:concat($url, xdmp:url-encode(xdmp:get-request-url()))
		else ()
};

declare function jqstore:start() {
	let $request := xdmp:get-request-field("originalRequest",())
	let $trunc := fn:substring-before($request,'?')
	let $trunc := if(fn:ends-with($trunc,'/')) then fn:substring($trunc,1,fn:string-length($trunc) - 1) else $trunc
	let $paths := fn:subsequence(fn:tokenize(fn:substring($trunc,fn:string-length($config:path)),"/"),2)
    (:let $type := xdmp:set-response-content-type("text/json"):)
	return 
	(
		for $i in $paths return fn:concat('[',$i,']'),
		for $n in xdmp:get-request-field-names()
		where $n != "originalRequest"
		return fn:concat('{',$n,'=',fn:string-join(xdmp:get-request-field($n),','),'}')
	)
};